import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { RuleEditService } from './edit.service';

import { Util } from '../../../common/util';

import * as moment from 'moment';
import * as _ from 'lodash'

@Component({
	selector: 'rule-edit',
	templateUrl: './edit.component.html',
	styleUrls: ['./edit.component.scss'],
	providers: [RuleEditService]
})
export class RuleEditComponent implements OnInit {
	@Input() public rule: any = {};

	@Input() public loadList: any;

	@Output() refreshList: EventEmitter<any> = new EventEmitter<any>();

	public codeEditor: any = null;

	public testResult: any = null;

	public progress_width: any = 30;

	public progress_state: any = '';

	public codeIsNull: any = '';

	public isActive: any = '';

	constructor(
		private ruleEditService: RuleEditService,
		private util: Util,

	) { }

	hideCron() {
		// let that = this;
		if (window['$']('div').hasClass('popover')) {
			window['$']('#btn-cron').trigger("click");
		}
		// window['$']('#cron').val(that.rule.cron);

	}
	changeTab() {
		let that = this;
		if (!that.codeEditor) {
			var indep_ace_lib_path = "/assets/vendor/ace-builds/src-noconflict";
			window['ace'].require("ace/config").set("workerPath", indep_ace_lib_path)
			window['ace'].require("ace/ext/language_tools");
			that.codeEditor = window['ace'].edit("editor");
			that.codeEditor.session.setMode("ace/mode/javascript");
			that.codeEditor.setTheme("ace/theme/twilight");
			that.codeEditor.$blockScrolling = Infinity;
			that.codeEditor.setOptions({
				minLines: 20,
				maxLines: 20,
				enableBasicAutocompletion: true,
				enableLiveAutocompletion: true
			})
		}
		that.codeEditor.on("change", function () {
			that.rule.order = that.codeEditor.getValue();
			if (that.codeEditor.getValue() == '') {
				window['$']('#save_btn').attr("disabled", "disabled");
			} else if (window['$']('#name').val().length != 0) {
				window['$']('#save_btn').removeAttr("disabled", "disabled")
			}
		});
		window['$']('#name').on("keyup", function () {
			if (that.codeEditor.getValue() == '') {
				window['$']('#save_btn').attr("disabled", "disabled");
			}

		})
		that.codeEditor.setValue(that.rule.order ? that.rule.order : "");
	}

	tabActive() {
		window['$']("#tab2").removeClass('active');
		window['$']("#tabTwoContent").attr('aria-expanded', "false");
		window['$']("#tab1").addClass('active');
		window['$']("#tabOneContent").attr('aria-expanded', "true");
		window['$']("#tab_1").addClass('active');
		window['$']("#tab_2").removeClass('active');
	}

	initUpload() {
		window['$'](function () {

			var url = window.location.hostname === '',
				uploadButton = window['$']('<button/>')
					.addClass('btn btn-primary')
					.prop('disabled', true)
					.text('Processing...')
					.on('click', function () {
						var $this = window['$'](this),
							data = $this.data();
						$this
							.off('click')
							.text('Abort')
							.on('click', function () {
								$this.remove();
								data.abort();
							});
						data.submit().always(function () {
							$this.remove();
						});
					});
			window['$']('#fileupload').fileupload({
				url: url,
				dataType: 'json',
				autoUpload: false,
				acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
				maxFileSize: 999000,
				// Enable image resizing, except for Android and Opera,
				// which actually support image resizing, but fail to
				// send Blob objects via XHR requests:
				disableImageResize: /Android(?!.*Chrome)|Opera/
					.test(window.navigator.userAgent),
				previewMaxWidth: 100,
				previewMaxHeight: 100,
				previewCrop: true
			}).on('fileuploadadd', function (e, data) {
				data.context = window['$']('<div/>').appendTo('#files');
				window['$'].each(data.files, function (index, file) {
					var node = window['$']('<p/>')
						.append(window['$']('<span/>').text(file.name));
					if (!index) {
						node
							.append('<br>')
							.append(uploadButton.clone(true).data(data));
					}
					node.appendTo(data.context);
				});
			}).on('fileuploadprocessalways', function (e, data) {
				var index = data.index,
					file = data.files[index],
					node = window['$'](data.context.children()[index]);
				if (file.preview) {
					node
						.prepend('<br>')
						.prepend(file.preview);
				}
				if (file.error) {
					node
						.append('<br>')
						.append(window['$']('<span class="text-danger"/>').text(file.error));
				}
				if (index + 1 === data.files.length) {
					data.context.find('button')
						.text('Upload')
						.prop('disabled', !!data.files.error);
				}
			})
				// .on('fileuploadprogressall', function (e, data:any) {
				//             var progress= parseInt(data.loaded / data.total * 100, 10);
				//             window['$']('#progress .progress-bar').css(
				//                 'width',
				//                 progress + '%'
				//             );
				//         })
				.on('fileuploaddone', function (e, data) {
					window['$'].each(data.result.files, function (index, file) {
						if (file.url) {
							var link = window['$']('<a>')
								.attr('target', '_blank')
								.prop('href', file.url);
							window['$'](data.context.children()[index])
								.wrap(link);
						} else if (file.error) {
							var error = window['$']('<span class="text-danger"/>').text(file.error);
							window['$'](data.context.children()[index])
								.append('<br>')
								.append(error);
						}
					});
				}).on('fileuploadfail', function (e, data) {
					window['$'].each(data.files, function (index) {
						var error = window['$']('<span class="text-danger"/>').text('File upload failed.');
						window['$'](data.context.children()[index])
							.append('<br>')
							.append(error);
					});
				}).prop('disabled', !window['$'].support.fileInput)
				.parent().addClass(window['$'].support.fileInput ? undefined : 'disabled');
		});

	}
	ngOnInit() {
		// 执行规则
		window['$']("#cron").cronGen();
		window['$']('.modal').modal({ backdrop: false, show: false });
		this.initUpload();

	}

	ngDoCheck() {

		window['$']('#cron_fake').val(window['$']('#cron').val())
	}
	createOrUpdate() {
		// this.rule.order = this.codeEditor.getValue();
		// this.rule.cron = window['$']("#cron").val();
		// this.ruleEditService.editRule(this.rule).subscribe(data => {

		// 	if (data) {
		// 		console.log(this.rule);
		// 		window['swal']('提示', '操作成功', 'success');
		// 		window['$'](".rule-edit-modal").modal('hide');
		// 		this.refreshList.emit();
		// 		this.tabActive();
		// 	}
		// });
		let code = window['$'].trim(this.codeEditor.getValue())
		if (code.length !== 0) {
			this.rule.order = this.codeEditor.getValue();
			this.rule.cron = window['$']("#cron").val();
			this.ruleEditService.editRule(this.rule).subscribe(data => {

				if (data) {
					console.log(this.rule);
					window['swal']('提示', '操作成功', 'success');
					window['$'](".rule-edit-modal").modal('hide');
					this.refreshList.emit();
					this.tabActive();
				}
			});
		}

	}

	runTest() {
		let postBody: any = {
			"name": window['$']('#name').val(),
			"cron": window['$']("#cron").val(),
			"order": this.codeEditor.getValue()
		}
		if (this.codeEditor.getValue() == '') {
			this.codeIsNull = true;
			return;
		}
		this.ruleEditService.testScript(postBody).subscribe(data => {
			if (data) {
				let postBody = {
					"jobId": data.id
				}
				this.getTestResult(postBody);
			}
		})


	}
	resetProgress() {
		this.progress_width = 0;
		this.progress_state = '';
		this.codeIsNull = false;
	}
	getTestResult(postBody) {
		console.log('postbody' + postBody);
		let that = this;
		this.ruleEditService.testView(postBody).subscribe(data => {
			// console.log(data)
			if (data && data != 'success') {
				if (data.state == 'failed') {
					window['$']('#save_btn').attr("disabled", "disabled");
				}
				this.testResult = data;
				this.progress_width = data.progress;
				this.progress_state = data.state;
			} else {
				setTimeout(function () {
					that.getTestResult(postBody);
				}, 1000);
			}
		})
	}

}
